package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenScan greenScan;

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanWmNews(Integer id) {
        log.info("成功接收到文章的自动审核消息，待审核的文章id: {}", id);
        // 1. 判断文章id是否为空
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "待审核的文章id为空");
        }
        // 2. 根据id查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在，自动审核失败");
        }
        // 3. 判断文章的状态  必须是 1 (待审核)  (避免重复消费)
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())) {
            log.info("当前文章状态 为: {}   不是待审核状态，无需审核",wmNews.getStatus());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不是待审核状态，自动审核失败");
        }
        // 4. 开始审核
        // 4.0 抽取文章中 所有的文本内容 和 所有的图片内容
        Map<String, Object> contentAndImages = parseContentAndImages(wmNews);
        // 4.1 DFA 进行自管理敏感词审核    2 有敏感词不通过     通过继续下一步
        boolean sensitiveScan = handleSensitive((String)contentAndImages.get("content"),wmNews);
        if (!sensitiveScan){
            log.info("文章审核未通过，原因: 内容中包含敏感词,文章id: {}", id);
            return;
        }
        // 4.2 阿里云的文本审核  2 有违规词汇    3 不确定/aliyun未调用成功   通过继续下一步
        boolean scanText = handleTextScan((String)contentAndImages.get("content"),wmNews);
        if(!scanText){
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含违规词汇,文章id: {}", id);
            return;
        }
        // 4.3 阿里云的图片审核  2 有违规图片    3 不确定/aliyun未调用成功   通过继续下一步
        List<String> images = (List<String>)contentAndImages.get("images");
        if (!CollectionUtils.isEmpty(images)) {
            boolean scanImages = handleImageScan(images,wmNews);
            if(!scanImages){
                // 返回false代表审核不成功   结束处理
                log.info("文章审核未通过，原因: 图片中包含违规信息,文章id: {}", id);
                return;
            }
        }
        // 5. 如果全部审核通过，将文章状态改为 8 自动审核通过
        updateWmNews(WmNews.Status.SUCCESS.getCode(),"审核通过",wmNews);
        // 6. 根据文章的发布时间，发送延迟消息 用于定时发布文章( 9 已发布)
        long remainTime = wmNews.getPublishTime().getTime() - new Date().getTime();
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setHeader("x-delay", remainTime<=0?0:remainTime);
                        return message;
                    }
                }
                );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
    }

    /**
     * 待审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            switch (scanResult.getSuggestion()){
                case "block":
                    // 失败
                    updateWmNews(WmNews.Status.FAIL.getCode(), "文章图片中违规信息: "+scanResult.getLabel() ,wmNews);
                    break;
                case "review":
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章图片中有不确定因素，转为人工审核" ,wmNews);
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，转为人工审核" ,wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 人工审核
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用失败，转为人工审核" ,wmNews);
        }
        return flag;
    }

    /**
     * 待审核文本
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    updateWmNews(WmNews.Status.FAIL.getCode(), "文章内容中有违规信息" ,wmNews);
                    break;
                case "review":
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章内容中有不确定信息，转为人工审核" ,wmNews);
                    break;
                case "pass":
                    flag = true;
                    break;
                default:
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，转为人工审核" ,wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核失败，转为人工审核");
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云文本审核失败，转为人工审核" ,wmNews);
        }
        return flag;
    }

    /**
     * 文章的所有文本内容 敏感词审核
     * @param content
     * @return
     */
    private boolean handleSensitive(String content,WmNews wmNews) {
        boolean flag = true;
        ResponseResult<List<String>> sensitivesResult = adminFeign.sensitives();
        if (!sensitivesResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
        List<String> sensitives = sensitivesResult.getData();
        //TODO Redis 设置
        SensitiveWordUtil.initMap(sensitives);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (!CollectionUtils.isEmpty(map)){
            updateWmNews(WmNews.Status.FAIL.getCode(), "文章中包含敏感词: "+map ,wmNews);
            flag = false;
        }
        return flag;
    }

    private void updateWmNews(Short status,String reason,WmNews wmNews){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 抽取文章中所有的文本内容和图片内容
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> parseContentAndImages(WmNews wmNews) {
        Map<String, Object> result = new HashMap<>();
        String contentMapList = wmNews.getContent();
        // 1. 抽取文章中所有的文本内容
        List<Map> maps = JSON.parseArray(contentMapList, Map.class);
        String content = maps.stream().filter(map -> "text".equals(map.get("type")))
                .map(map -> String.valueOf(map.get("value")))
                .collect(Collectors.joining("_hmtt_"));
        content += "_hmtt_" + wmNews.getTitle() + "_hmtt_" + wmNews.getLabels();
        // 2. 抽取文章中所有的图片内容
        List<String> images = maps.stream().filter(map -> "image".equals(map.get("type")))
                .map(map -> String.valueOf(map.get("value")))
                .distinct()
                .collect(Collectors.toList());
        String coverStr = wmNews.getImages();
        if (StringUtils.isNotBlank(coverStr)){
            List<String> coverImages = Arrays.stream(coverStr.split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            images.addAll(coverImages);
        }
        List<String> imagesResult = images.stream().distinct().collect(Collectors.toList());
        result.put("content",content);
        result.put("images",imagesResult);
        return result;
    }
}